package com.pro01.apirednote.controller;

import com.pro01.apirednote.pojo.Result;
import jakarta.servlet.annotation.MultipartConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/files")
@Slf4j
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;

    // 单文件上传接口
    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 确保上传目录存在
            Path uploadDir = Paths.get(uploadPath);
            Files.createDirectories(uploadDir);

            // 生成唯一文件名
            String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path destPath = uploadDir.resolve(filename);
            file.transferTo(destPath.toFile());

            return Result.success("/uploads/" + filename);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    // 多文件上传接口
    // 多文件上传接口（推荐用 MultipartFile[] 兼容性更好）
    @PostMapping("/upload/multi")
    public Result<List<String>> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            log.warn("⚠️ 多文件上传请求为空");
            return Result.error("未上传任何文件");
        }

        log.info("✅ 进入了多文件上传接口，收到 {} 个文件", files.length);

        List<String> urls = new ArrayList<>();
        try {
            // 确保上传目录存在
            Path uploadDir = Paths.get(uploadPath);
            Files.createDirectories(uploadDir);

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    log.warn("⚠️ 忽略空文件: {}", file.getOriginalFilename());
                    continue;
                }

                String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
                Path destPath = uploadDir.resolve(filename);
                file.transferTo(destPath.toFile());
                urls.add("/uploads/" + filename);
            }

            return Result.success(urls);
        } catch (IOException e) {
            log.error("❌ 多文件上传失败", e);
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}